var mysql = require("mysql");

var connect_pool = null;
function connectToDB(){
    connect_pool = mysql.createPool({
        host: "127.0.0.1",
        port: 3306,
        database: "email",
        user: "root",
        password: ""
    })
}
function WriteEmial(email){
    var sqlStr = "insert into email_table(`title`,`email`,`content`,`time`) values ('"+email.title+"','"+email.email+"','"+email.content+"','"+email.time+"')";
    connect_pool.getConnection(function(err, conn) {
		if (err) { // 如果有错误信息
			
			return null;
		}
        conn.query(sqlStr,(err,res,fileds)=>{
            conn.release();
            if(err){
                console.log(err);
                return null;
            }
        })
    });
}
function modifyEmail(id){
    var sqlStr = " UPDATE email_table SET send=1 WHERE id="+id;
    connect_pool.getConnection(function(err, conn) {
		if (err) { // 如果有错误信息
			console.log("connect err:",err);
			return null;
		}
        conn.query(sqlStr,(err,res,fileds)=>{
            conn.release();
            if(err){
                console.log(err);
                return null;
            }
        })
    });
}
function getTodayEmail(callback){
    var sqlStr = "SELECT * FROM email_table WHERE TO_DAYS(time) = TO_DAYS(NOW()) AND send = 0"
    connect_pool.getConnection(function(err, conn) {
		if (err) { // 如果有错误信息
			console.log("connect err:",err);
			callback && callback(null);
            return;
		}
        conn.query(sqlStr,(err,res,fileds)=>{
            conn.release();
            if(err){
                console.log(err);
                callback && callback(null);
                return;
            }
            callback && callback(res);
        })
    });
}
module.exports = {
    connectToDB: connectToDB,
    WriteEmail: WriteEmial,
    ReadEmail: getTodayEmail,
    SendFinish: modifyEmail
}